package com.liuceng.zen.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.liuceng.zen.mapper.RptFrontAdGroupDailyMapper;
import com.liuceng.zen.pojo.domain.GdtAdGroup;
import com.liuceng.zen.pojo.domain.Member;
import com.liuceng.zen.pojo.domain.RptFrontAdGroup;

@Service
public class RptFrontAdGroupService {
  @Autowired
  RptFrontAdGroupDailyMapper rptFrontAdGroupDailyMapper;

  public Map<String, Object> findRptData(Integer memberId, Integer crtSize) {
    Map<String, Object> params = new HashMap<>();
    params.put("memberId", memberId);
    params.put("crtSize", crtSize);
    // 获取当前账号某一创意规格的广告组的信息
    return rptFrontAdGroupDailyMapper.findRptData(params);
  }

  public BigDecimal findCost(Map<String, Object> rptData) {
    if (rptData == null || rptData.get("total_cost") == null)
      return new BigDecimal(0);

    return (BigDecimal) rptData.get("total_cost");
  }

  public int findPv(Map<String, Object> rptData) {
    if (rptData == null)
      return 0;
    return Integer.parseInt(rptData.get("pv") == null ? "0" : rptData.get("pv").toString());
  }

  public int findPc(Map<String, Object> rptData) {
    if (rptData == null)
      return 0;
    return Integer.parseInt(rptData.get("pc") == null ? "0" : rptData.get("pc").toString());
  }


  public List<RptFrontAdGroup> convert2FrontAdGroup(Member member, List<GdtAdGroup> adgroups) {
    List<RptFrontAdGroup> fAdGroups = new ArrayList<>();
    for (GdtAdGroup adgroup : adgroups) {
      // 填充每个group中的相关值
      // 把创意尺寸作为广告组尺寸
      Integer crtSize = adgroup.getCrtSize();
      RptFrontAdGroup fAdGroup = new RptFrontAdGroup(adgroup);
      // 组合广告计划名
      String campaignName = member.getCityStr() + member.getCompanyName()
          + (GdtAdGroup.SITESET_TYPE_PC == adgroup.getSitesetType() ? "PC" : "Mob");
      fAdGroup.setCname(campaignName);
      // 组合广告名称
      fAdGroup.setAname(campaignName + "-" + crtSize);
      // 获取这个广告组尺寸下的总花费，曝光量，点击量
      Map<String, Object> rptData = findRptData(member.getId(), crtSize);
      //花费小数保留
      BigDecimal cost = findCost(rptData);
      fAdGroup.setCost(cost);
      // 曝光量
      int pv = findPv(rptData);
      // 点击量
      int pc = findPc(rptData);
      fAdGroup.setStartAt(adgroup.getBeginAt());
      fAdGroup.setPv(pv);
      fAdGroup.setPc(pc);
      fAdGroup.setAid(adgroup.getAid());
      // 点击率
      fAdGroup.setCtr(pv == 0 ? new BigDecimal(0) : new BigDecimal(pc * 100.0 / pv));
      // 点击均价
      fAdGroup.setCostPerClick(
          pc == 0 ? new BigDecimal(0) : cost.divide(new BigDecimal(pc), 3, RoundingMode.UP));
      fAdGroups.add(fAdGroup);
    }
    return fAdGroups;
  }

}
